package com.example.last.controller;

import cn.hutool.core.io.FileUtil;
import com.example.last.common.Result;
import com.example.last.common.enums.ErrorCode;
import com.example.last.exception.CustomException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/file")
public class FilesController {
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws Exception {
        // 找到文件的位置
        String filePath = System.getProperty("user.dir") + "/files/";
        String realPath = filePath + fileName; // D:\项目实战\小白做毕设\代码\code2025\files\404.jpg
        boolean exist = FileUtil.exist(realPath);
        if (!exist) {
            throw new CustomException(ErrorCode.FILE_ERROR);
        }

        // 读取文件的字节流
        byte[] bytes = FileUtil.readBytes(realPath);
        ServletOutputStream os = response.getOutputStream();
        // 输出流对象把文件写出客户端
        os.write(bytes);
        os.flush();
        os.close();
    }

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
        // 找到文件的位置
        String filePath = System.getProperty("user.dir") + "/files/";
        if (!FileUtil.isDirectory(filePath)) {
            FileUtil.mkdir(filePath);
        }
        byte[] bytes = file.getBytes(); // 文件的原始名称
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        // 写入文件
        FileUtil.writeBytes(bytes, filePath + fileName);
        String url = "http://localhost:8080/api/file/download/" + fileName;
        return Result.success(url);
    }
}
